<template>
  <!-- 结算管理-结算单录入 -->
  <div class="warp">
    <jz-table ref="table" :tableData="tableData" :headList="tableHead" :butList="butList"
      :searchData="searchConf" selection :tableConf="tableConf" :pageConf="page"
      @pageChange="pageChange(1)" @sortChange="sortChange">
      <template #topAppend>
        <el-button class="search" type="primary" size="mini" @click="pageChange('search')">
          高级查询 <i class="el-icon-search"></i>
        </el-button>
      </template>
      <!-- 操作日期-格式 -->
      <template #operdt="{row}">{{ row.operdt|cdate_f('yyyy-MM-dd hh:mm:ss') }}</template>
      <!-- 更多操作 -->
      <template #more="{row}">
        <i class="more el-icon-edit" @click.stop="moreHandle(1, row)" title="编辑"></i>
        <i class="more el-icon-delete" @click.stop="moreHandle(2, row)" title="删除"></i>
        <i class="more el-icon-zoom-in" @click.stop="moreHandle(3, row)" title="查看"></i>
      </template>
    </jz-table>
    <!-- 高级搜索 -->
    <jz-search :dialog="searchDialog" :fields="tableHead|fieds_f"
      fId="prop" fName="label" :data="params.filters&&params.filters.rules" />
    <!-- 修改|新增|查询 -->
    <c-dialog :dialog="dialog" :form="form" :rows="{gutter:10}"
      :cols="{span:12,xs:24}" :formOption="formOption" :formItem="formItem">

      <template #item_projectId> <!-- 项目 -->
        <div class="pro-selete">
          <el-select v-model="form.projectId" size="mini" disabled>
            <el-option :label="form.projectname" :value="form.projectId"></el-option>
          </el-select>
          <el-button v-if="!formOption.disabled" type="primary" size="mini" @click="openDialog(1)" icon="el-icon-more" plain />
        </div>
      </template>
      <template #item_sentfmid> <!-- 结算单位 -->
        <div class="pro-selete">
          <el-select v-model="form.sentfmid" size="mini" disabled>
            <el-option :label="form.sentfmname" :value="form.sentfmid"></el-option>
          </el-select>
          <el-button v-if="!formOption.disabled" type="primary" size="mini" @click="openDialog(2)" icon="el-icon-more" plain />
        </div>
      </template>
      <template #item_operdt> <!-- 操作日期 -->
        <el-date-picker disabled v-model="form.operdt" style="width: 100%;" type="datetime" />
      </template>
      <template #item_userid> <!-- 操作员 -->
        <el-select v-model="form.userid" style="width: 100%;" disabled>
          <el-option v-for="(item, index) in sysUser" :key="index"
            :label="item.usename" :value="item.userid"></el-option>
        </el-select>
      </template>
      <!-- 列表配置 -->
      <template #append>
        <jz-table :tableData="tData" :headList="tHead" :butList="tBut" :tableConf="tConf">
          <!-- 费用项目 -->
          <template #syscodedid="{row}">
            <span v-if="formOption.disabled">{{ row.CodeName }}</span>
            <el-select v-else v-model="row.syscodedid" size="mini">
              <el-option v-for="(item, ind) in costPro" :key="ind"
                :label="item.CodeName" :value="item.CodeID">
              </el-option>
            </el-select>
          </template>
          <template #machineid="{row, $index}"> <!-- 机械名称 -->
            <span v-if="formOption.disabled">{{ row.machinename }}</span>
            <div v-else class="pro-selete">
              <el-input v-model="row.machinename" placeholder="选择机械" size="mini" disabled>
                <el-button slot="append" type="primary" size="mini" @click.native.stop="openDialog(3,$index)" icon="el-icon-search" plain />
              </el-input>
            </div>
          </template>
          <!-- 金额 -->
          <template #acc="{row}">
            <span v-if="formOption.disabled">{{ row.acc }}</span>
            <el-input-number v-else v-model="row.acc" :min="0" size="mini" />
          </template>
          <!-- 备注 -->
          <template #remark="{row}">
            <span v-if="formOption.disabled">{{ row.remark }}</span>
            <el-input v-else v-model="row.remark" size="mini" />
          </template>
          <!-- 更多操作 -->
          <template #more="{$index}">
            <i class="more el-icon-delete" @click.stop="moreHandle(4, $index)" title="删除"></i>
          </template>
        </jz-table>
      </template>
    </c-dialog>
    <!-- 弹窗--选择 -->
    <template>
      <!-- 选择机械 -->
      <c-dialog v-if="proConf.id==3" :dialog="proDialog" footerNe spaceAuto>
        <!-- <c-machine child @on-change="proHandle" /> -->
      </c-dialog>
      <!-- 项目-单位 选择 -->
      <c-pro-list v-else :dialog="proDialog" @confirm="proHandle" v-bind="proConf" />
    </template>
  </div>
</template>
<script>
// import cProList from '../base/components/pro_list' // 选择项目-子模块
// import cMachine from '../base/machine' // 选择机械-子模块
export default {
  name: 'balance_statementIn',
  data() {
    return {
      // 数据       字段配置         table配置      功能区按钮-配置
      tableData: [], tableHead: [], tableConf: {}, butList: [],
      // 搜索-单       高级搜索     搜索条件    分页      删除id
      searchConf: {}, searchDialog: {}, params: {}, page: {}, ids: [],
      // 弹窗     表单数据   表单配置         表单子-配置   操作员-列表
      dialog: [], form: {}, formOption: {}, formItem: {}, sysUser: [],
      // 部位配置     弹窗-列表数据 字段配置  列表配置    功能区配置
      proDialog: {}, tData: [], tHead: [], tConf: {}, tBut: [],
      // 弹窗列表-配置 费用项目
      proConf: {}, costPro: []
    }
  },
  computed: {
    http() { return this.$http.balance } // http-远程请求
  },
  // components: { cProList, cMachine },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.initTable() // 初始化-相关配置
      // this.getPageList() // 获取分页数据
      // this.getSysUser() // 获取操作员列表
      // this.getCostPro() // 获取费用项目
      this.tableConf.maxHeight = window.innerHeight - (95 + 39 + 35 + 20)
    },
    // 请求-获取列表
    async getPageList() {
      let params = this.page
      params = Object.assign(params, this.params)
      const res = await this.http.statement.getPageList(params)
      if (res) {
        this.tableData = res.rows || []
        this.page.total = res.records
      }
    },
    // 请求-费用列表
    async getCostPro() {
      const params = { DataType: 'ClaimChargeItem' }
      const res = await this.$http.other.getCodeList(params)
      if (res) {
        this.costPro = res
      }
    },
    // 请求-获取费用列表
    async getBalanceList(id) {
      const res = await this.http.statement.getBalanceList({ id })
      if (res) {
        this.tData = res
      }
    },
    // 请求-删除 单/批
    deletAll(ids) {
      const pAll = []
      ids = ids || this.ids
      ids.forEach(id => {
        pAll.push(this.http.statement.delete({ currentId: id }))
      })
      Promise.all(pAll).then(res => {
        if (res && res.length) {
          this.$notify.success({ title: '提示', message: this.$api_code.res.MSG_3 })
          this.getPageList()
        }
      })
    },
    // 请求-操作员列表
    async getSysUser() {
      const res = await this.$http.other.getOperMsg()
      if (res) {
        this.sysUser = res
      }
    },
    // 设置-状态
    async setSwitch(params) {
      const res = await this.http.station.setSwitch(params)
      if (res) {
        const type = res.Code == 1 ? 'success' : 'error'
        const msg = res.Code == 1 ? this.$api_code.res.MSG_1 : res.Msg
        this.$notify[type]({ title: '提示', message: msg })
      }
    },
    // 分页-回调
    pageChange(type) {
      switch (type) {
        case 1: // 分页
          this.getPageList()
          break
        case 'search': // 高级搜索
          this.searchDialog.open = true
          break
        case 'refresh': // 刷新
          this.params = {}
          // this.$msg('刷新成功！')
          this.getPageList()
          break
      }
    },
    // 功能区-回调
    butHandle(row) {
      switch (row.id) {
        case 'add': { // 新增
          const { userid } = this.$store.getters.currentUser
          this.form = {
            userid: userid, operdt: new Date().toJSON(),
            projectId: '', projectname: '', sentfmid: '', sentfmname: ''
          }
          this.updateField()
          this.dialog.isOpen = true
          this.dialog.title = '新增-结算单'
          this.tData = []
          break
        }
        case 'dels': // 批-删除
          if (!this.ids.length) {
            this.$msg('请至少选择一行数据！', 'warning')
          } else {
            this.deletAll()
          }
          break
        case 'search': // 单-搜索
          this.page.curPage = 1
          this.page.limit = 10
          Object.assign(this.params, { searchKey: row.value, '_search': false })
          this.getPageList()
          break
        case 'searchM': { // 高级-搜索
          this.page.curPage = 1
          this.page.limit = 10
          Object.assign(this.params, { filters: row.value, '_search': true })
          this.getPageList()
          break
        }
        case 'oneSelete': // 单选-change回调
          this.$refs.table.setSelection(2, row.value)
          break
        case 'multSelete': { // 多选-change回调
          const { value: list } = row
          this.ids = list.map(o => o.balancehedno)
          break
        }
        case 'addCost': // 新增费用
          this.tData.push({
            syscodedid: '', machineid: '', machinename: '', acc: 0, remark: ''
          })
          break
      }
    },
    // 开关 - 回调
    switchHandle(row) {
      const { stationid, cancelflg } = row
      this.setSwitch({ stationid, cancelflg })
    },
    // open 弹窗
    openDialog(type, index) {
      switch (type) {
        case 1: { // 选择项目
          this.proConf = {
            id: type, currValue: this.form.projectId, currKey: 'uniqueID'
          }
          this.proConf.http = this.$http.proInfo.basicInfo
          this.proDialog.title = '选择项目'
          this.proDialog.isOpen = true
          break
        }
        case 2: { // 选择-结算单位
          this.proConf = {
            id: type, currValue: this.form.sentfmid, currKey: 'SupplyID',
            fnName: 'getValidSupply'
          }
          this.proConf.tableHead = [
            { type: 'index' },
            { label: '供应商编号', prop: 'SupplyCode', sortable: 'custom' },
            { label: '供应商姓名', prop: 'SupplyDesc', sortable: 'custom' }
          ]
          this.proConf.http = this.$http.base.supply
          this.proDialog.title = '选择-结算单位'
          this.proDialog.isOpen = true
          break
        }
        case 3: // 选择-机械
          this.proConf = { id: type, index }
          this.proDialog.title = '选择-机械'
          this.proDialog.isOpen = true
          break
      }
    },
    // 弹窗选择-回调
    proHandle(row) {
      switch (this.proConf.id) {
        case 1: // 选择项目
          this.form.projectId = row.uniqueID
          this.form.projectname = row.projectname
          this.proDialog.isOpen = false
          break
        case 2: // 选择结算单位
          this.form.sentfmid = row.SupplyID
          this.form.collectunit = row.SupplyID
          this.form.sentfmname = row.SupplyDesc
          this.proDialog.isOpen = false
          break
        case 3: { // 选择机械
          const ind = this.proConf.index
          this.tData[ind].machineid = row.machineid
          this.tData[ind].machinename = row.machinename
          this.proDialog.isOpen = false
          break
        }
      }
    },
    // 排序-自定义
    sortChange({ column, prop, order }) {
      this.params.sidx = order ? prop : ''
      this.params.sord = order ? order.slice(0, -6) : ''
      this.getPageList()
    },
    // table 更多-操作
    moreHandle(type, row) {
      switch (type) {
        case 1: // 编辑
          this.form = row
          this.form.projectId = row.projectid
          this.form.sentfmid = row.collectunit
          this.form.sentfmname = row.balunitname
          this.getBalanceList(row.balancehedno)
          this.updateField()
          this.dialog.isOpen = true
          this.dialog.title = '修改-结算单'
          break
        case 2: // 删除
          this.$confirm(`您正在删除单据【${row.balancehedno}】，请再次确认？`, '确认信息')
            .then(_ => {
              this.deletAll([row.balancehedno])
            })
            .catch(_ => {})
          break
        case 3: // 查看
          this.form = row
          this.form.sentfmname = row.balunitname
          this.getBalanceList(row.balancehedno)
          this.formOption.disabled = true
          this.updateField()
          this.dialog.isOpen = true
          this.dialog.title = '查看-结算单'
          break
        case 4: // 删除-弹窗-列表
          this.tData.splice(row, 1)
          break
      }
    },
    // 弹窗-确定-提交保存
    confirm(formRefs) {
      if (this.formOption.disabled) { // 查看-禁止提交
        this.dialog.isOpen = false
        return
      }
      formRefs.validate(async valid => {
        if (valid) {
          this.dialog.loading = true
          const params = { head: this.form, detail: this.tData }
          const res = await this.http.statement.addOrUpdate(params)
          this.dialog.loading = false
          if (res.Code == 1) {
            this.$notify.success({ title: '提示', message: res.Msg })
            this.dialog.isOpen = false
            this.getPageList() // 更新数据
          } else {
            this.$notify.error({ title: '提示', message: res.Msg })
          }
        }
      })
    },
    // table-field
    updateField() {
      this.tBut = []
      this.tHead = [
        { label: '费用项目', prop: 'syscodedid' },
        { label: '机械名称', prop: 'machineid' },
        { label: '金额', prop: 'acc' },
        { label: '备注', prop: 'remark' }
      ]
      if (!this.formOption.disabled) {
        this.tHead.push({ label: '删除', prop: 'more' })
        this.tBut = [{ id: 'addCost', name: '新增费用', type: 'primary', size: 'xs', callback: this.butHandle }]
      }
    },
    // table - 初始化配置
    initTable() {
      // 分页-配置
      this.page = {
        open: true, limit: 10, total: 0, curPage: 1, otherHandle: this.pageChange
      }
      // table-配置
      this.tableConf = {
        stripe: true,
        rowStyle: ({ row: o }) => o.cancelflg == 1 && { color: 'red' },
        selectionChange: v => this.butHandle({ id: 'multSelete', value: v }),
        currentChange: v => this.butHandle({ id: 'oneSelete', value: v })
      }
      // 功能区-按钮配置
      this.butList = [
        { id: 'add', callback: this.butHandle },
        { id: 'dels', callback: this.butHandle }
      ]
      // 功能区-单-搜索配置
      this.searchConf = {
        id: 'search', callback: this.butHandle
      }
      // 弹窗-高级搜索-配置
      this.searchDialog = {
        open: false, callback: v => this.butHandle({ id: 'searchM', value: v })
      }
      // table - 字段配置
      this.tableHead = [
        { label: '单据号', prop: 'balancehedno', sortable: 'custom' },
        { label: '项目名称', prop: 'projectname', sortable: 'custom', hide: true },
        { label: '结算单位', prop: 'collectunit', sortable: 'custom' },
        { label: '结算金额', prop: 'acc', sortable: 'custom' },
        { label: '操作员', prop: 'userid', sortable: 'custom' },
        { label: '操作日期', prop: 'operdt', sortable: 'custom' },
        { label: '操作', prop: 'more' }
      ]
      // dialog - 弹窗配置- 新增|修改|查询
      this.dialog = {
        isOpen: false, width: '70%', loading: false, modalClose: false,
        confirm: this.confirm, title: '',
        closeHandle: _ => { this.formOption.disabled = false; this.dialog.title = '' }
      }
      // 弹窗-项目选择
      this.proDialog = { isOpen: false, title: '', top: '10vh' }
      // 表单验证
      const rulesStr = this.$commUtil.getRulesStr
      const rules = {
        change: { required: true, message: '请选择？' },
        sheight: { pattern: /^(\d+)(\.\d{1,2})?$/, message: '保留两位小数', trigger: 'blur' }
      }
      // 表单配置
      this.formOption = { isIcon: true, labelW: '70px', size: 'small', rules: rules, disabled: false }
      // 表单子-配置
      this.formItem = [
        { label: '项目', prop: 'projectId', rules: rules.change },
        { label: '收款银行', prop: 'collectbank', rules: rulesStr(true, 80) },
        { label: '结算单位', prop: 'sentfmid', rules: rules.change },
        { label: '收款账号', prop: 'collectacc', rules: rulesStr(true, 80) },
        { label: '备注', prop: 'remark', iType: 'textarea', cols: { span: 24 }},
        { label: '操作员', prop: 'userid' }, { label: '操作日期', prop: 'operdt' }
      ]
      // 弹窗-列表-功能区
      this.tConf = { maxHeight: 200, currRow: false, showSummary: true }
    }
  },
  filters: {
    // 搜索-字段过滤
    fieds_f(list) {
      return list.filter(o => o.prop && o.prop != 'more')
    }
  }
}
</script>
<style lang="scss" scoped>
@import '~@/styles/mixin';
// @import url('@/styles/mixin');
// 容器
.warp{
  @include warp;
  // 高级搜索
  .search{
    float: right;
    margin-right: 20px;
  }
  // 更多操作
  i.more{
    // color: #5cb6ff;
    margin: 0 3px;
    font-size: 18px;
    cursor: pointer;
    &:hover{
      color: #5cb6ff;
    }
  }
  // 表单操作
  .pro-selete{ // 选择项目
    ::v-deep {
      >.el-select{
        width: 100%;
        padding-right: 44px;
      }
      >.el-button{
        position: absolute;
        right: 0;
        font-size: 20px;
        padding: 5px;
        border-radius: 20px;
      }
    }
  }
}
</style>
